<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin/home' }"
        >首页</el-breadcrumb-item
      >
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="16">
          <!-- 搜索与添加区域 -->
          <el-input
            :placeholder="'请输入' + selected"
            v-model="input"
            clearable
          >
            <el-select
              v-model="selected"
              class="select"
              slot="prepend"
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getCollegeList(true)"
            ></el-button>
            <el-button
              slot="append"
              icon="el-icon-refresh-right"
              @click="getCollegeList(false)"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加菜品</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="selectVisibale = true"
            >筛选</el-button
          >
        </el-col>
        <el-col :span="2">
            <el-button v-waves :loading="downloadLoading" type="primary" icon="el-icon-download" @click="handleDownload">
                导出为Excel
            </el-button>
        </el-col>
      </el-row>
      <!-- 列表区域 -->
      <el-table :data="collegeListShow" border stripe  default-sort>
        <!-- 自定义索引 -->
        <!-- <el-table-column type="index"> </el-table-column> -->
        <el-table-column prop="id" label="菜品编号" sortable></el-table-column>
        <el-table-column prop="food" label="菜品名"></el-table-column>
        <el-table-column prop="price" label="价格"></el-table-column>
        <el-table-column prop="desc" label="描述"></el-table-column>
        <el-table-column prop="stock" label="库存"></el-table-column>
        <el-table-column prop="img" label="图片">
          <template slot-scope="{row}">
            <img v-if="row.img" :src="row.img"  class="imageConst" >
           <i v-else  class="imageConst"></i>
           <!-- <img :src="constImage" class="imageConst"/> -->
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型">  
            <template slot-scope="{row}">
                <el-tag>{{ row.type }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="rec" label="推荐指数">
          <template slot-scope="{row}">
            <el-rate v-model="row.rec"></el-rate>
        </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="{row}" >
            <el-tag :type="row.status | statusFilter">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            >
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteCollege(scope.row.id)"
            >
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页栏 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.collegeList.length"
      >
      </el-pagination>
    </el-card>
    <!-- 添加菜品对话框 -->
    <el-dialog
      title="添加菜品"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form label-position="left"
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="90px"
      >
        <el-form-item label="菜品名" prop="food">
          <el-input
            v-model="addForm.food"
            placeholder="请输入菜品名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
            <el-input
              v-model="addForm.price"
              placeholder="请输入价格"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="库存" prop="stock">
            <el-slider
            v-model="addForm.stock"
            :step="10">
          </el-slider>
          </el-form-item>
          <el-form-item label="类型" prop="type">
                <el-select
                v-model="addForm.type"
                placeholder="请选择"
                >
                <el-option
                    v-for="item in typeOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                >
                </el-option>
                </el-select>
          </el-form-item>
          <el-form-item label="推荐指数" prop="rec">
            <el-rate v-model="addForm.rec"></el-rate>
          </el-form-item>
          <el-form-item label="上架" prop="status">
            <el-radio v-model="addForm.status" label="上架">是</el-radio>
            <el-radio v-model="addForm.status" label="下架">否</el-radio>
          </el-form-item>
          <el-form-item label="图片" prop="img">
            <!-- <input type='file' accept='image/*' id='imgFile' multiple/>  -->
            <!-- <input type="file" name="image" accept="image/*" @change='onchangeImgFun'/> -->
            <!-- <img  alt="" :src='imgStr'/> -->
                <el-upload class="avatar-uploader" action="#" :show-file-list="false"
                  :before-upload="beforeAvatarUpload" 
                  >
                  <img v-if="imgStr" :src="imgStr" >
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input
              v-model="addForm.desc"
              placeholder="描述"
              :autosize="{ minRows: 2, maxRows: 4}" 
              type="textarea"
              clearable
            ></el-input>
          </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCollege"> 确 定 </el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      title="编辑菜品信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form label-position="left"
        :model="editForm"
        ref="editFormRef"
        label-width="90px"
      >
      <el-form-item label="菜品编号" prop="id">
        <el-input
          v-model.number="editForm.id"
          placeholder="请输入菜品编号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="菜品名" prop="food">
        <el-input
          v-model="editForm.food"
          placeholder="请输入菜品名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="价格" prop="price">
          <el-input
            v-model="editForm.price"
            placeholder="请输入价格"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-slider
            v-model="editForm.stock"
            :step="10">
          </el-slider>
        </el-form-item>
        <el-form-item label="类型" prop="type">
            <el-select
            v-model="editForm.type"
            placeholder="请选择"
            >
            <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="推荐指数" prop="rec">
          <el-rate v-model="editForm.rec"></el-rate>
        </el-form-item>
        <el-form-item label="上架" prop="status">
          <el-radio v-model="editForm.status" label="上架">是</el-radio>
          <el-radio v-model="editForm.status" label="下架">否</el-radio>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input
            v-model="editForm.desc"
            placeholder="描述"
            clearable
            :autosize="{ minRows: 2, maxRows: 4}" 
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCollege"> 确 定 </el-button>
      </span>
    </el-dialog>


    <el-dialog
    title="多条件筛选"
    :visible.sync="selectVisibale"
    width="50%"
    @close="selectVisibale = false"
  >
    <!-- 内容主题区域 -->
    <el-form label-position="left"
      :model="selectForm"
      label-width="90px"
    >
    <el-form-item label="最低价格" prop="valueL">
      <el-input
        v-model="selectForm.valueL"
        placeholder="请输入最低价格"
        clearable
      ></el-input>
    </el-form-item>
    <el-form-item label="最高价格" prop="valueH">
      <el-input
        v-model="selectForm.valueH"
        placeholder="请输入最高价格"
        clearable
      ></el-input>
    </el-form-item>
    <el-form-item label="库存下限" prop="stockL">
        <el-input
          v-model="selectForm.stockL"
          placeholder="请输入库存下限"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="库存上限" prop="stockH">
        <el-input
          v-model="selectForm.stockH"
          placeholder="请输入库存上限"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="类型" prop="type">
          <el-select
          v-model="selectForm.kind"
          placeholder="请选择"
          >
          <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.label"
              :value="item.value"
          >
          </el-option>
          </el-select>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="selectVisibale = false">取 消</el-button>
      <el-button type="primary" @click="multiselect"> 确 定 </el-button>
    </span>
  </el-dialog>
  </div>
</template>
<script>
import axios from 'axios'

var constList = [
  {
        id: 0,
        food: 'apple',
        price: '12',
        desc: '好吃',
        stock: 20,
        type: '水果',
        rec: 4.5,
        img:'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png',
        status: '上架'
  },
  {
        id: 1,
        food: 'hhh',
        price: '13',
        desc: '好吃',
        stock: 50,
        type: '盒饭',
        rec: 4.5,
        img:'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png',
        status: '下架'
  }
]


export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        '上架': 'success',
        '下架': 'info',
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      selectForm:{
        valueL:'',
        valueH:'',
        stockL:'',
        stockH:'',
        kind:''
      },
      selectVisibale:false,
    constImage:'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png',
    downloadLoading: false,
    value1:null,
    errorStr:'',
    imgStr:'',
      options: [
        {
          value: '菜品编号',
          label: '菜品编号',
        },
        {
          value: '菜品名',
          label: '菜品名',
        },
        {
          value: '菜品类型',
          label: '菜品类型',
        },
      ],
      typeOptions:[
        {
            id: 0,
            value: '主食',
            label: '主食',
        },
        {
            id: 1,
            value: '热汤',
            label: '热汤',
        },
        {
            id: 2,
            value: '蔬菜',
            label: '蔬菜',
        },
        {
            id: 3,
            value: '盒饭套餐',
            label: '盒饭套餐',
        },
      ],
      selectedType:'',
      selected: '菜品编号', // 搜索选择
      input: '', // 搜索输入框
      collegeList: [], // 院系列表
      collegeListShow: [], // 展示的院系列表
      total: 0, // 院系列表总数
      currentPage: 1, // 当前页面
      pageSize: 5, // 每页展示列表数
      // 控制添加对话框显示与隐藏
      addDialogVisible: false,
      // 添加院系的表单数据
      addForm: {
        food: '',
        price: '',
        desc: '',
        stock: 0,
        type: '',
        rec: 0,
        img:'',
        status:''
      },
      delid:{
        id:0,
      },
      // 添加表单的验证规则
      addFormRules: {
        food: [
          { required: true, message: '请输入菜品名', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '菜品名长度在2~20个字符之间',
            trigger: 'blur',
          },
        ],
      },
      // 控制修改对话框显示与隐藏
      editDialogVisible: false,
      // 查询到的院系信息
      editForm: {
        food: '',
      },
      // 修改表单的验证规则
      editFormRules: {
        food: [
          { required: false, message: '请输入菜品名', trigger: 'blur' },
          {
            min: 1,
            max: 20,
            message: '菜品名长度在1~20个字符之间',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    this.getCollegeList()
  },
  methods: {
    // 获取院系列表
    async getCollegeList(search) {
      console.log("get list again")
      var query = {}
      if (search) {
        console.log("have search")
        if (this.selected === '菜品编号') {
          query = { id: this.input }
        } else if (this.selected === '菜品名') {
          query = { food: this.input }
        } else if( this.selected == '菜品类型') {
          query = { type : this.input}
        }
        console.log(query)
        axios.post(`/business/anyfood`,query)
        .then((res) => {
          console.log(res)
          var list = []
          list.push(res.data)
          this.collegeListShow = res.data
          if (res.status !== 200) return this.$message.error('获取列表失败')
        })
      } else {
        console.log("no search")
        console.log(query)
        axios.post(`/business/allfood/detailed`,query)
        .then((res) => { 
          console.log(res)
          this.collegeList = res.data;
          // this.collegeList = constList;
          this.currentPage = 1;
          var start = 0;
          var end = start + this.pageSize;
          this.collegeListShow = this.collegeList.slice(start, end)
          console.log("show data")
          console.log(this.collegeListShow)
        if (res.status !== 200) return this.$message.error('获取列表失败')
        })
      }
    },
    multiselect(){
      this.selectVisibale = false
      console.log(this.selectForm)
      axios.post(`/business/select`,this.selectForm)
      .then((res)=>{
        console.log("select result")
        console.log(res)
        if(res.status !== 200) this.$message.error("获取列表失败")
        this.collegeList = res.data;
          // this.collegeList = constList;
          this.currentPage = 1;
          var start = 0;
          var end = start + this.pageSize;
          this.collegeListShow = this.collegeList.slice(start, end)
      })
    },
    beforeAvatarUpload(file) {
				console.log(file)

      console.log("before")
      // 获取图片的大小，做大小限制有用
      let imgSize = file.size
      console.log(imgSize)
      var _this = this // this指向问题，所以在外面先定义
      // 比如上传头像限制5M大小，这里获取的大小单位是b
      if (imgSize <= 50 * 1024) {
        // 合格
        _this.errorStr = ''
        console.log('大小合适')
        // 开始渲染选择的图片
        // 本地路径方法 1
        // this.imgStr = window.URL.createObjectURL(e.target.files[0])
        // console.log(window.URL.createObjectURL(e.target.files[0])) // 获取当前文件的信息

        // base64方法 2
        var reader = new FileReader()
        reader.readAsDataURL(file) // 读出 base64
        reader.onloadend = function () {
          // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
          var dataURL = reader.result
          console.log(dataURL)
          _this.imgStr = dataURL
          _this.addForm.img = dataURL
          this.addForm.img = dataURL
          console.log("addForm-img")
          console.log(this.addForm.img)
          // 下面逻辑处理
        }
      } else {
        console.log('大小不合适')
        _this.errorStr = '图片大小超出范围'
      }
				this.imgStr = URL.createObjectURL(file);
				return false
			},
    // 监听对话框关闭事件
    addDialogClosed() {
      // 重置表单
      this.$refs.addFormRef.resetFields()
    },
    handleDownload() {
      this.downloadLoading = true
      import('./vendor/Export2Excel').then(excel => {
        const tHeader = ['菜品编号', '菜品名称', '菜品价格', '菜品类型', '存货','描述']
        const filterVal = ['id', 'food', 'price', 'type', 'stock','desc']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '菜品信息'
        })
        this.downloadLoading = false
      })
    },
    onchangeImgFun (e,fileList) {
      var file = e.target.files[0]
      console.log("onchange")
      console.log(file)
      // 获取图片的大小，做大小限制有用
      let imgSize = file.size
      console.log(imgSize)
      var _this = this // this指向问题，所以在外面先定义
      // 比如上传头像限制5M大小，这里获取的大小单位是b
      if (imgSize <= 50 * 1024) {
        // 合格
        _this.errorStr = ''
        console.log('大小合适')
        // 开始渲染选择的图片
        // 本地路径方法 1
        // this.imgStr = window.URL.createObjectURL(e.target.files[0])
        // console.log(window.URL.createObjectURL(e.target.files[0])) // 获取当前文件的信息

        // base64方法 2
        var reader = new FileReader()
        reader.readAsDataURL(file) // 读出 base64
        reader.onloadend = function () {
          // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
          var dataURL = reader.result
          console.log(dataURL)
          _this.imgStr = dataURL
          _this.addForm.img = dataURL
          // 下面逻辑处理
        }
      } else {
        console.log('大小不合适')
        _this.errorStr = '图片大小超出范围'
      }
    },
    formatJson(filterVal) {
      return this.collegeList.map(v => filterVal.map(j => {
          return v[j]
      }))
    },
    // 添加菜品
    addCollege() {
      this.$refs.addFormRef.validate(async (valid) => {
        var query = {
            food: this.addForm.food,
            price : this.addForm.price,
            desc: this.addForm.desc,
            stock: this.addForm.stock,
            type: this.addForm.type,
            img: this.addForm.img,
            rec: this.addForm.rec,
            status: this.addForm.status,
        }
        this.collegeList.push(query)
        this.currentPage = 1;
        var start = 0;
        var end = start + this.pageSize;
        this.collegeListShow = this.collegeList.slice(start, end)
        console.log("add")
        console.log(query)
        if (!valid) return
        // 校验正确则发起请求
        //----后端----
        axios.post(`/business/addfood`,query)
        .then((res) => { 
        console.log("return state")
        console.log(res.data)
        if (res.data.state === 0) {
          this.$message.success('添加成功！')
          this.addDialogVisible = false
          console.log("---")
          // 重新获取院系列表
          this.getCollegeList()
        }
        else this.$message.error('添加失败！\n' + res.detail[0])
        })
        // this.addDialogVisible = false
        // console.log("---")
        // // 重新获取院系列表
        // this.getCollegeList()
      })
    },
    // 编辑
    async showEditDialog(e) {
      console.log(e)
      this.editDialogVisible = true
      var query = {id : e}
      axios.post(`/business/onefood`,query)
        .then((res) => { 
            this.editForm = res.data  
            if (res.data.state !== 0) return this.$message.error('获取列表失败')
        })
    },
    // 监听修改对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改信息
    editCollege() {
      this.$refs.editFormRef.validate(async (valid) => {
        var query = {
            id: this.editForm.id,
            food: this.editForm.food,
            price : this.editForm.price,
            desc: this.editForm.desc,
            stock: this.editForm.stock,
            type: this.editForm.type,
            rec: this.editForm.rec,
            status:this.editForm.status
        }
        console.log("editForm-query")
        console.log(this.editForm)
        if (!valid) return
        // 校验正确则发起请求
        axios.put(`/business/changefood`,this.editForm)
        .then((res) => { 
            this.editForm = res.data  
            if (res.data.state !== 0)  this.$message.error('修改失败！')
            this.$message.success('更新成功！')
            this.editDialogVisible = false
            // 重新获取院系列表
            this.getCollegeList()
        })
      })
    },
    // 删除院系
    deleteCollege(idt) {
        var query = {id : idt}
        this.delid.id = idt
      // 弹框提示
      this.$confirm('此操作将永久删除该菜品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          console.log(this.delid)
          // 确定删除
          axios.post(`/business/delfood`,this.delid)
        .then((res) => { 
          console.log(res)
            if (res.data.state != 0)
            return this.$message({
              type: 'error',
              message: '删除失败!',
            })
            this.$message({
            type: 'success',
            message: '删除成功!',
            })
            // 刷新院系列表
            this.getCollegeList()
        })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 监听分页变化
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      let start = 0
      let end = start + pageSize
      this.collegeListShow = this.collegeList.slice(start, end)
    },
    // 监听当前页面变化
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      let start = (currentPage - 1) * this.pageSize
      let end = start + this.pageSize
      this.collegeListShow = this.collegeList.slice(start, end)
    },
  },
}
</script>
<style lang="less" scoped>
.el-col-4 {
    width: 10%;
}
.box-card {
    width: 1250px;
    height: 600px;
}
.select {
  width: 120px;
}
.pagination {
  margin-top: 15px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.imageConst {
  width: 50px;
  height: 50px;
  margin-left: 10px;
}
</style>